# 导入
import time
import re
from wxauto import WeChat
from urllib.parse import urlparse, parse_qs
import requests
from urllib.parse import urlencode, urlunparse

# 导入
from DrissionPage import Chromium,ChromiumOptions
from DrissionPage.common import Settings

Settings.set_raise_when_ele_not_found(True)



# 群名列表 逗号分割，群面有表情的 先修改备注
listen_list = [
  '羊毛'
]
# cookie列表  前面自定义名字，后面对应的cookie
cookies = {
    '账号6700':'jd_eid=jdd03QD6V52CZWYIOG5SXPVIR5TLKMHFNGTSC5F624XWCQK7MHEZB5ML6ZLM7RB2CTVJ3VKI2RGSFYQHFT4SGMTZEOHFGQIAAAAMTXXYSS3AAAAAADQK4B35LVVG7CMX;unionuuid=V2_ZwFGDUZWERImAEJQfhtfBjcAQgkVB0EUfFtEU3kQCwAIABNeR1ZKFnUIR1ByGFlqZwIVQkBfXBV0CllWegxJ;_reuuid=3e4123fda3b54132be11658ceb6e421f;guid=69435f1bc329f6215711b6dd9a6186341acd7f2bdc0fb4f8d589aa3df2f12575;unionuuid=V2_NwdFCBFfRxxzARZXfh8MDDcDF1QRUhATJwBHBi9LXAEIABNeR1dCFHwIQlZ4GVVqZwIVQkBfXBV0CllWegxJ;guid=78fcb91f171f78491ed9173c49c91bdbe6cf44dffb5e1cb36d59f7594d48cfa3;qrsc=3;s_pin=jd_49735ef72e5a6;[object Object]=undefined;cud=24d664f9e19da727da4d667bae231c80;o2State={%22webp%22:true%2C%22avif%22:true};DeviceSeq=2a80a9ffde774911904725a370ed21ed;mp=18323406700;shshshfpa=36b3c51e-37ab-fa8a-1b0c-9ebf2e474541-1728369516;shshshfpx=36b3c51e-37ab-fa8a-1b0c-9ebf2e474541-1728369516;jcap_dvzw_fp=jQiH3u6f-4Cp0a03I4Y9DhzheFijm4_Nn_oZ6oN_oHF22HmuLWLMp-Q_koSeIZ7lgJHklj_GRtM4ZXCSe12Sbw==;whwswswws=;__jdu=1736388058043635363064;areaId=4;ipLoc-djd=4-48207-0-0;PCSYCityID=CN_500000_500100_0;lstoken=jxxafwl8;s_key=AAJnhMwXADAJlps2vxm1cE0vK_poPAY8-3qMLuD4SZkCwLD42i3QoSGkULBMFifI4eOPv0UKCH0;pt_st=1_dAvfKlHV1SFExIMoWLIxatpgy-MVwp183bwhY1a7g7YlCwo8YO0RykkwLP_i7AXIutFo6eSQoLr1eEIKdGGFvTSZUV7gRv2QuflNKplA5pjxGYgu7t3L2-OsH23bW-fjSYzric6MXwUGn5kjTPsfMFydSArQjunLcHoeB_Biat9S6opjmb4jgP6UsSMHMC2Qv4EKv4RdSgVss1F2cVyFSx4o2asB8JVc_3rpQo20;_t=uEry4+Jy5dy7PuTS7cf0NAga34c+6rxJ7/cJIm2tFBY=;QRCodeKey=AAEAIFF0y9b6NdKa_4lBj97_ncG3Y8As7f-KGQwiz99pDaVE;JSESSIONID=51E27D215ED1F5F25FB0751D5FF772DC.s1;TrackID=1gyZ03JJiYYk8zCP7i-kPHcVrMjriNFQPCqsfeEJ03HM1MLDz3sbmJAqGWI9oAoIC6cd7XLbOGY5ksXduw0aI21wqearPLVhDHRRcgAF464I;thor=1D6BBEF28AF9AB3471D291CE9E649DAFE8D3A323014E8FFFD57BD3D28FE76D4FF2B67B20916349A80B00B3497186476C8D9B41DE8A67A637685B486186D34BE2952B4608ABD570829015650C0401EB2C266D07B608493446C033146A18C8A81CD5233E4D50CBB5F15B59DE9B2A7089A9D5F57E3C01EEC5852C75584B2291C50691579E0CB275A28F4254A7F8D76B179FE416A7EFE4DACF8500D554752CCBCDCE;light_key=AASBKE7rOxgWQziEhC_QY6yaF7MPrE5vZaLDWlgWG8pTsHm08NPch_fmZ9eFHqpOZrXFcARx;pinId=15maKJIfAtMqVfMVvcn4JbV9-x-f3wj7;pin=jd_49735ef72e5a6;unick=loveljlj;ceshi3.com=201;_tp=unnVIIcqGlkK7D0KM%2Fm%2Fojy8aSkzRXerTykzvt2BH4k%3D;_pst=jd_49735ef72e5a6;umc_count=1;UC_SEM_REFER=https://www.baidu.com/other.php?sc.0s0000K7v7v6sgT56Jlm7Ok7ryoeMz4ooHu4Ex2l8pTqD70pFt4rM2TpyUpELXiBKEUMTDZgkFIOfBO6RzAKSh7E8putuLH-9knZVEPftfSis4ocXkth35Et7SgM_UUG1fN9zkSuW1_iUfSM4QrB7xs9bNwenYSIeR6KIZNYUX2HtgsCf7xmAG_SAKnOVwfyqDCS2nWVh_-_rTsySYgEhwc4v5xh.Db_NR2Ar5Od66sw5I7M9CE9exQQTBaPrMLek8sHfGmEukmnSPtgjN6uBl3cM8BSq1AHu_LUJePSeoAS6MeLng_3_APtgjN6uB4UPxAeWuj_8EutX1IEEELuPXwPS4PerkhZk8lYZnNR2Ar5jkus4PXZFo3rj6t_Vz7PHV2XgZJyAp7WFuEvU60.TLFWgv-b5HDkrfK1ThPGujYknHb0THvSJUpo0ZwV5UlGVJ_0IgP-T-qYXgK-5H00mywxIZ-suHY10ZIEThfqEJhvJsKzmLmqn0KdThkxpyfqnHRvrj6dnjTdnsKVINqGujYkPWm3PjmLrfKVgv-b5HDYnjmkrj6d0AdYTAkxpyfqnHc4Pjc0TZuxpyfqn0KGuAnqiDFK0ZKGujYk0APGujY1rH00mLFW5HmLP16&dt=1736827239&wd=%E4%BA%AC%E4%B8%9C&tpl=tpl_12942_36979_0&l=1568850753&ai=0_427460789_1_1&us=linkVersion%3D1%26compPath%3D10036.0-10032.0%26label%3D%25E4%25B8%25BB%25E6%25A0%2587%25E9%25A2%2598%26linkType%3D%26linkText%3D%25E4%25BA%25AC%25E4%25B8%259C%25E5%25AE%2598%25E7%25BD%2591%2520%25E5%258F%2588%25E5%25A5%25BD%25E5%258F%2588%25E4%25BE%25BF%25E5%25AE%259C;CSID=RjxsSXVWWg1VRgZYWRUPRgpsdi4ieV5cEwtRBEMLXQFqeH5zcX93cBRTOkFRWFNIR3Z7fAhGVRdkbhp6Uls3VUdXQF9DW1laZnZmd3o%3d;unpl=JF8EAMhnNSttWkgGUU4KGBcQSlhdW1gISB5ROzNWUQ9fQlQGHFYZQhN7XlVdWRRKFx9vYhRUXlNKVQ4eAisSEXteXVdZDEsWC2tXVgQFDQ8VXURJQlZAFDNVCV9dSRZRZjJWBFtdT1xWSAYYRRMfDlAKDlhCR1FpMjVkXlh7VAQrAh0QF0lUXV9ZAUoSAWhlAVZaWkpTACsDKxUge21UXFsIShMzblcEZB8MF1QEEwsbEF1LW1ZZXwFCFgdmZgBWWlpPVgIZAxwXIEptVw;__jdv=76161171|baidu-pinzhuan|t_288551095_baidupinzhuan|cpc|0f3d30c8dba7459bb52f2eb5eba8ac7d_0_32ced924104844128ceeb4c68126e3a2|1736827308220;xapieid=jdd03JJHCJH3QNGBRJG56VNTFCIRFHDQBBEXHMBD6JOENEDE2NOFYUITURQ4RZJBTFW53XHJ2BTLGWAIITW6WSHZAO6UJPEAAAAMUML5KNCQAAAAADIYU3G5AADJWTYX;rkv=1.0;3AB9D23F7A4B3C9B=JJHCJH3QNGBRJG56VNTFCIRFHDQBBEXHMBD6JOENEDE2NOFYUITURQ4RZJBTFW53XHJ2BTLGWAIITW6WSHZAO6UJPE;3AB9D23F7A4B3CSS=jdd03JJHCJH3QNGBRJG56VNTFCIRFHDQBBEXHMBD6JOENEDE2NOFYUITURQ4RZJBTFW53XHJ2BTLGWAIITW6WSHZAO6UJPEAAAAMUMNIEGBIAAAAACQMRJNWSGZSPJIX;_gia_d=1;autoOpenApp_downCloseDate_jd_independent_coupon_openapp=1736832992359_1;__jda=76161171.1736388058043635363064.1736388058.1736827242.1736832991.9;__jdb=76161171.2.1736388058043635363064|9.1736832991;__jdc=76161171;cvt=5;csn=1;flash=3_nW2KwaBNEd8fbUBEtrmxDB4hc5HWp2mpdam8T6xEQ1bY_4Xslv8nLwRKkGaV3YzOGtdJzkJk9rVoaYkTEnXThsXiXDVvpbwwnBLJyMIeukZMqpgrsxSZVKqfeYWKBy46RLV6fH12P461a0l2pQxkhWxS5yL7o2Mf9EREmsddhar6_vOF3AB1pq**;UseCorpPin=jd_49735ef72e5a6;shshshfpb=BApXSLFdZYPFARWsOxewUPqnF98iVgfSbBmp3kjli9xJ1MrXTGIG2',
    '账号67001':'jd_eid=jdd03QD6V52CZWYIOG5SXPVIR5TLKMHFNGTSC5F624XWCQK7MHEZB5ML6ZLM7RB2CTVJ3VKI2RGSFYQHFT4SGMTZEOHFGQIAAAAMTXXYSS3AAAAAADQK4B35LVVG7CMX;unionuuid=V2_ZwFGDUZWERImAEJQfhtfBjcAQgkVB0EUfFtEU3kQCwAIABNeR1ZKFnUIR1ByGFlqZwIVQkBfXBV0CllWegxJ;_reuuid=3e4123fda3b54132be11658ceb6e421f;guid=69435f1bc329f6215711b6dd9a6186341acd7f2bdc0fb4f8d589aa3df2f12575;unionuuid=V2_NwdFCBFfRxxzARZXfh8MDDcDF1QRUhATJwBHBi9LXAEIABNeR1dCFHwIQlZ4GVVqZwIVQkBfXBV0CllWegxJ;guid=78fcb91f171f78491ed9173c49c91bdbe6cf44dffb5e1cb36d59f7594d48cfa3;qrsc=3;s_pin=jd_49735ef72e5a6;[object Object]=undefined;cud=24d664f9e19da727da4d667bae231c80;o2State={%22webp%22:true%2C%22avif%22:true};DeviceSeq=2a80a9ffde774911904725a370ed21ed;mp=18323406700;shshshfpa=36b3c51e-37ab-fa8a-1b0c-9ebf2e474541-1728369516;shshshfpx=36b3c51e-37ab-fa8a-1b0c-9ebf2e474541-1728369516;jcap_dvzw_fp=jQiH3u6f-4Cp0a03I4Y9DhzheFijm4_Nn_oZ6oN_oHF22HmuLWLMp-Q_koSeIZ7lgJHklj_GRtM4ZXCSe12Sbw==;whwswswws=;__jdu=1736388058043635363064;areaId=4;ipLoc-djd=4-48207-0-0;PCSYCityID=CN_500000_500100_0;lstoken=jxxafwl8;s_key=AAJnhMwXADAJlps2vxm1cE0vK_poPAY8-3qMLuD4SZkCwLD42i3QoSGkULBMFifI4eOPv0UKCH0;pt_st=1_dAvfKlHV1SFExIMoWLIxatpgy-MVwp183bwhY1a7g7YlCwo8YO0RykkwLP_i7AXIutFo6eSQoLr1eEIKdGGFvTSZUV7gRv2QuflNKplA5pjxGYgu7t3L2-OsH23bW-fjSYzric6MXwUGn5kjTPsfMFydSArQjunLcHoeB_Biat9S6opjmb4jgP6UsSMHMC2Qv4EKv4RdSgVss1F2cVyFSx4o2asB8JVc_3rpQo20;_t=uEry4+Jy5dy7PuTS7cf0NAga34c+6rxJ7/cJIm2tFBY=;QRCodeKey=AAEAIFF0y9b6NdKa_4lBj97_ncG3Y8As7f-KGQwiz99pDaVE;JSESSIONID=51E27D215ED1F5F25FB0751D5FF772DC.s1;TrackID=1gyZ03JJiYYk8zCP7i-kPHcVrMjriNFQPCqsfeEJ03HM1MLDz3sbmJAqGWI9oAoIC6cd7XLbOGY5ksXduw0aI21wqearPLVhDHRRcgAF464I;thor=1D6BBEF28AF9AB3471D291CE9E649DAFE8D3A323014E8FFFD57BD3D28FE76D4FF2B67B20916349A80B00B3497186476C8D9B41DE8A67A637685B486186D34BE2952B4608ABD570829015650C0401EB2C266D07B608493446C033146A18C8A81CD5233E4D50CBB5F15B59DE9B2A7089A9D5F57E3C01EEC5852C75584B2291C50691579E0CB275A28F4254A7F8D76B179FE416A7EFE4DACF8500D554752CCBCDCE;light_key=AASBKE7rOxgWQziEhC_QY6yaF7MPrE5vZaLDWlgWG8pTsHm08NPch_fmZ9eFHqpOZrXFcARx;pinId=15maKJIfAtMqVfMVvcn4JbV9-x-f3wj7;pin=jd_49735ef72e5a6;unick=loveljlj;ceshi3.com=201;_tp=unnVIIcqGlkK7D0KM%2Fm%2Fojy8aSkzRXerTykzvt2BH4k%3D;_pst=jd_49735ef72e5a6;umc_count=1;UC_SEM_REFER=https://www.baidu.com/other.php?sc.0s0000K7v7v6sgT56Jlm7Ok7ryoeMz4ooHu4Ex2l8pTqD70pFt4rM2TpyUpELXiBKEUMTDZgkFIOfBO6RzAKSh7E8putuLH-9knZVEPftfSis4ocXkth35Et7SgM_UUG1fN9zkSuW1_iUfSM4QrB7xs9bNwenYSIeR6KIZNYUX2HtgsCf7xmAG_SAKnOVwfyqDCS2nWVh_-_rTsySYgEhwc4v5xh.Db_NR2Ar5Od66sw5I7M9CE9exQQTBaPrMLek8sHfGmEukmnSPtgjN6uBl3cM8BSq1AHu_LUJePSeoAS6MeLng_3_APtgjN6uB4UPxAeWuj_8EutX1IEEELuPXwPS4PerkhZk8lYZnNR2Ar5jkus4PXZFo3rj6t_Vz7PHV2XgZJyAp7WFuEvU60.TLFWgv-b5HDkrfK1ThPGujYknHb0THvSJUpo0ZwV5UlGVJ_0IgP-T-qYXgK-5H00mywxIZ-suHY10ZIEThfqEJhvJsKzmLmqn0KdThkxpyfqnHRvrj6dnjTdnsKVINqGujYkPWm3PjmLrfKVgv-b5HDYnjmkrj6d0AdYTAkxpyfqnHc4Pjc0TZuxpyfqn0KGuAnqiDFK0ZKGujYk0APGujY1rH00mLFW5HmLP16&dt=1736827239&wd=%E4%BA%AC%E4%B8%9C&tpl=tpl_12942_36979_0&l=1568850753&ai=0_427460789_1_1&us=linkVersion%3D1%26compPath%3D10036.0-10032.0%26label%3D%25E4%25B8%25BB%25E6%25A0%2587%25E9%25A2%2598%26linkType%3D%26linkText%3D%25E4%25BA%25AC%25E4%25B8%259C%25E5%25AE%2598%25E7%25BD%2591%2520%25E5%258F%2588%25E5%25A5%25BD%25E5%258F%2588%25E4%25BE%25BF%25E5%25AE%259C;CSID=RjxsSXVWWg1VRgZYWRUPRgpsdi4ieV5cEwtRBEMLXQFqeH5zcX93cBRTOkFRWFNIR3Z7fAhGVRdkbhp6Uls3VUdXQF9DW1laZnZmd3o%3d;unpl=JF8EAMhnNSttWkgGUU4KGBcQSlhdW1gISB5ROzNWUQ9fQlQGHFYZQhN7XlVdWRRKFx9vYhRUXlNKVQ4eAisSEXteXVdZDEsWC2tXVgQFDQ8VXURJQlZAFDNVCV9dSRZRZjJWBFtdT1xWSAYYRRMfDlAKDlhCR1FpMjVkXlh7VAQrAh0QF0lUXV9ZAUoSAWhlAVZaWkpTACsDKxUge21UXFsIShMzblcEZB8MF1QEEwsbEF1LW1ZZXwFCFgdmZgBWWlpPVgIZAxwXIEptVw;__jdv=76161171|baidu-pinzhuan|t_288551095_baidupinzhuan|cpc|0f3d30c8dba7459bb52f2eb5eba8ac7d_0_32ced924104844128ceeb4c68126e3a2|1736827308220;xapieid=jdd03JJHCJH3QNGBRJG56VNTFCIRFHDQBBEXHMBD6JOENEDE2NOFYUITURQ4RZJBTFW53XHJ2BTLGWAIITW6WSHZAO6UJPEAAAAMUML5KNCQAAAAADIYU3G5AADJWTYX;rkv=1.0;3AB9D23F7A4B3C9B=JJHCJH3QNGBRJG56VNTFCIRFHDQBBEXHMBD6JOENEDE2NOFYUITURQ4RZJBTFW53XHJ2BTLGWAIITW6WSHZAO6UJPE;3AB9D23F7A4B3CSS=jdd03JJHCJH3QNGBRJG56VNTFCIRFHDQBBEXHMBD6JOENEDE2NOFYUITURQ4RZJBTFW53XHJ2BTLGWAIITW6WSHZAO6UJPEAAAAMUMNIEGBIAAAAACQMRJNWSGZSPJIX;_gia_d=1;autoOpenApp_downCloseDate_jd_independent_coupon_openapp=1736832992359_1;__jda=76161171.1736388058043635363064.1736388058.1736827242.1736832991.9;__jdb=76161171.2.1736388058043635363064|9.1736832991;__jdc=76161171;cvt=5;csn=1;flash=3_nW2KwaBNEd8fbUBEtrmxDB4hc5HWp2mpdam8T6xEQ1bY_4Xslv8nLwRKkGaV3YzOGtdJzkJk9rVoaYkTEnXThsXiXDVvpbwwnBLJyMIeukZMqpgrsxSZVKqfeYWKBy46RLV6fH12P461a0l2pQxkhWxS5yL7o2Mf9EREmsddhar6_vOF3AB1pq**;UseCorpPin=jd_49735ef72e5a6;shshshfpb=BApXSLFdZYPFARWsOxewUPqnF98iVgfSbBmp3kjli9xJ1MrXTGIG2'
}


# 获取微信窗口对象
wx = WeChat()
# 输出 > 初始化成功，获取到已登录窗口：xxxx

# 分割中文和url
def formaturlTokey(text):
    """
        从给定文本中提取描述和URL，并返回一个包含描述-链接对的列表。

        参数:
        text (str): 包含描述和URL的原始文本。

        返回:
        list: 包含元组（描述, URL）的列表。
        """
    # 正则表达式模式，用于查找所有以http或https开头的URL
    url_pattern = re.compile(r'https?://c[^\s]+')

    # 查找所有URL
    urls = url_pattern.findall(text)

    # 初始化一个列表来保存描述-链接对
    description_url_pairs = []

    # 遍历找到的所有URL
    start = 0
    for url in urls:
        # 找到当前URL在原始文本中的位置
        index = text.find(url, start)
        # 提取从上一个结束位置到当前URL开始位置之间的描述
        description = text[start:index].strip()
        # 添加描述-链接对到列表
        description_url_pairs.append((description, url))
        # 更新起始位置为当前URL结束位置之后
        start = index + len(url)

    # 如果最后一个URL之后还有剩余的文本，作为最后一个描述添加
    # if start < len(text):
    #     description_url_pairs.append((text[start:].strip(), ''))

    print(description_url_pairs)
    return description_url_pairs

# 获取url中的 key和id
def getkey(url):
    parsed_url = urlparse(url)
    query_params = parse_qs(parsed_url.query)
    key = query_params.get('key', [None])[0]  # 使用get方法并提供默认值以避免KeyError

    print(key)
    if key == None:
        linkKey = query_params.get('linkKey', [None])[0]
        print(linkKey)
        return ['linkkey',linkKey,'']
    else:
        role_id = query_params.get('roleId', [None])[0]
        return ['key', key, role_id]

def find_jdd_string(text):
    pattern = re.compile(r'=\b(jdd[^;]+)')

    # 查找匹配
    match = pattern.search(text)

    if match:
        return match.group(1)
    else:
        return None




# 领取
def getquan(ck,url):
    # 创建页面对象，并启动或接管浏览器

    for key, value in cookies.items():
        print('本次请求用户:', key)

        co = ChromiumOptions().auto_port()
        # 启动或接管浏览器，并创建标签页对象
        tab = Chromium(co).latest_tab
        tab.set.timeouts(3)
        # 跳转到登录页面
        tab.get(url)

        tab.set.cookies(cookies[key] + ';domain=.jd.com')
        tab.listen.start('api.m.jd.com/client.action')  # 开始监听，指定获取包含该文本的数据包

        # time.sleep(0.5)
        # 寻找立即领取按钮

        try:
            ele = tab.ele('.btn')
            ele.click()
            res = tab.listen.wait()  # 等待并获取一个数据包
            print(res.response.body)
            # JSON转对象
            # 关闭 tab
            tab.close()
        except :
            tab.close()
            print('没有找到。')

        # 点击领取按钮

        # page.ele('@value=立即领取').click()
    return True






for i in listen_list:
    wx.AddListenChat(who=i, savepic=False)

# 持续监听消息，并且收到消息后回复“收到”
wait = 0.2  # 设置1秒查看一次是否有新消息

time.sleep(1) #就是这里，等一会，大家自己试一下，估计再少一些也没问题
while True:

    msgs = wx.GetListenMessage()
    for chat in msgs:
        who = chat.who  # 获取聊天窗口名（人或群名）
        one_msgs = msgs.get(chat)  # 获取消息内容
        # 回复收到
        for msg in one_msgs:
            msgtype = msg.type  # 获取消息类型
            sender = msg.sender # 发送消息者
            content = msg.content  # 获取消息内容，字符串类型的消息内容
            print(f'【{who}】：{sender}:{content}')
            # ===================================================
            # 处理消息逻辑（如果有）
            #
            # 处理消息内容的逻辑每个人都不同，按自己想法写就好了，这里不写了
            #
            # ===================================================

            # 如果是好友发来的消息（即非系统消息等），则回复收到
            if msgtype == 'friend' or True:
                # 判断不同的优惠券 用不同的方式
                if 'coupon.m.jd.com/' in content:
                    print('检测到优惠券')
                    # 分割名字和url
                    objresult = formaturlTokey(content)
                    for desc, url in objresult:
                        # 提取url中的key和id
                        # parsed_url = urlparse(obj.url)
                        print('desc:::',desc, 'url:::',url)
                        keys = getkey(url)

                        # print(keys[0], keys[1], keys[2])

                        # 领取券
                        # print('本次请求用户:', key)
                        res = getquan(cookies, url)

                        # for key, value in cookies.items():
                        #     print('本次请求用户:',key)
                        #     res = getquan(cookies[key], url)
                        #     # print(res['data'])
                        #     try:
                        #         if res['data']['resultCode'] == 999:
                        #             print(
                        #                 '账号:' + key + ' 领取成功 该券满' + str(res["data"]["quota"]) + '-' + str(
                        #                     res["data"]["discount"]))
                        #
                        #
                        #     except Exception as e:
                        #         # print(f"An error occurred: {e}")
                        #         # 无论是否有错误发生，这里的代码都会被执行
                        #         print("可惜~发生错误了~")
                        #     finally:
                        #         print("-----------------------------------")
                        #         print(res)
                        #     time.sleep(0.1)

                # chat.SendMsg('收到')  # 回复收到
    time.sleep(wait)